package com.cx.service.serviceimp;

import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import com.cx.entity.Accounts;

import java.math.BigDecimal;
import java.util.List;

import com.cx.mapper.AccountsMapper;
import com.cx.service.AccountsService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AccountsServiceImpl implements AccountsService {

    @Resource
    private AccountsMapper accountsMapper;

    @Override
    public int deleteByPrimaryKey(Integer accountId) {
        return accountsMapper.deleteByPrimaryKey(accountId);
    }

    @Override
    public int insert(Accounts record) {
        return accountsMapper.insert(record);
    }

    @Override
    public int insertOrUpdate(Accounts record) {
        return accountsMapper.insertOrUpdate(record);
    }

    @Override
    public int insertOrUpdateSelective(Accounts record) {
        return accountsMapper.insertOrUpdateSelective(record);
    }

    @Override
    public int insertSelective(Accounts record) {
        return accountsMapper.insertSelective(record);
    }

    @Override
    public Accounts selectByPrimaryKey(Integer accountId) {
        return accountsMapper.selectByPrimaryKey(accountId);
    }

    @Override
    public int updateByPrimaryKeySelective(Accounts record) {
        return accountsMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Accounts record) {
        return accountsMapper.updateByPrimaryKey(record);
    }

    @Override
    public int updateBatch(List<Accounts> list) {
        return accountsMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<Accounts> list) {
        return accountsMapper.batchInsert(list);
    }


    @Transactional
    public void transfer(Integer fromAccountId, Integer toAccountId, Double amount) {
        Accounts fromAccount = accountsMapper.selectByPrimaryKey(fromAccountId);
        fromAccount.setAccountId(fromAccountId);
        Accounts toAccount = accountsMapper.selectByPrimaryKey(toAccountId);
        toAccount.setAccountId(toAccountId);

        if (fromAccount.getBalance().doubleValue() < amount) {
            throw new RuntimeException("Insufficient balance");
        }

        fromAccount.setBalance(fromAccount.getBalance().subtract(new BigDecimal(amount)));
        toAccount.setBalance(toAccount.getBalance().add(new BigDecimal(amount)));

        accountsMapper.updateByPrimaryKeySelective(fromAccount);
        // 这里会引发 ArithmeticException 并导致事务回滚
        int i = 1 / 0;
        accountsMapper.updateByPrimaryKeySelective(toAccount);
    }


}
